﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Threading.Tasks;
using BBICMS.WebUI.Filters;
using BBICMS.Model;
using BBICMS.Model.Enums;
using BBICMS.Infrastructure.Configs;
using BBICMS.Model.Security;
using System.Threading;
using BBICMS.DTO;
using AutoMapper;
using BBICMS.Application.ViewModels;

namespace BBICMS.WebUI.Areas.Admin.Controllers
{

    [SIGAuth]
    public class MenuController : BaseController
    {
              
        // GET: /Admin/Menu/ 
        public ActionResult Index()
        {
            IEnumerable<Category> menuCategories = _unit.Categories.GetCategoryByModelType(ModelType.MENU);   
            if (!User.IsInRole("创始人"))
            {
                menuCategories = menuCategories.Where(c => c.Id != SettingsManager.Menu.BackMenuCId);
                return View(menuCategories);
            }         
            return View(menuCategories);
        }

        /// <summary>
        /// 获取单组菜单
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<ActionResult> GetMenus(int categoryId)
        {
            var menus = await _unit.Menus.FindByAsync<int>((m => m.CategoryId == categoryId && m.ParentId == null), m => m.Importance, false, default(CancellationToken),(m => m.ChildMenus)); 
            return PartialView("_MenuList",menus);
        }

       [AllowAnonymous]
        public ActionResult LeftNavs(int categoryId)
        {
           
            var orgMenus = _unit.Menus.GetFilteredElements((m => m.CategoryId == categoryId && m.ParentId == null && m.Active), (m => m.ChildMenus));
            Menu vMenu = orgMenus.FirstOrDefault();
           
               
            MenuDTO dto = Mapper.Map<MenuDTO>(vMenu);
            List<MenuDTO> menus = Mapper.Map<List<MenuDTO>>(vMenu.ChildMenus.Where(m=>m.Active).OrderByDescending(m => m.Importance));


            //AutoMapper.Mapper.Map(orgMenus, dto);
            //AutoMapper.Mapper.Map((List<MenuDTO>)vMenu.ChildMenus.OrderByDescending(m => m.Importance), menus);
            //  var dto = _mapper.Map<MenuDTO>(vMenu);
            // menus = _mapper.Map<List<MenuDTO>>(vMenu.ChildMenus.OrderByDescending(m => m.Importance));
           

            dto.ChildMenus.Clear();
            menus.Insert(0, dto);

            return PartialView("_LeftNav", menus);
        }


        /// <summary>
        /// 面包屑
        /// </summary>
        [AllowAnonymous]
        public ActionResult Crumbs(string areaName,string controller,string action)
        {
            //Menu vMenu = _menuService.CurrenMenu(areaName, controller, action);
            //List<Menu> menus = new List<Menu>();
            //if(vMenu != null)
            //    RecursiveLoad(vMenu, menus);

            return PartialView("_Crumbs", _unit.Menus.CurrenMenuCrumbs(areaName, controller, action));
        }

        [HttpGet]     
        public ActionResult CreateMenu(int categoryId, int parentId)
        {
            var vMenu = new Menu();

      
            var newDto = Mapper.Map<MenuDTO>(vMenu);
        
            newDto.CategoryId = (int)categoryId;          
            newDto.ParentId = parentId;
            return PartialView("_MenuCreate", newDto);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult CreateMenu(MenuDTO menu)
        {

            if (ModelState.IsValid)
            {
            
                var vMenu = Mapper.Map<Menu>(menu);

                _unit.Menus.Add(vMenu);

                _unit.SaveChanges();

                AR.SetSuccess("已成功新增菜单");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
           
            AR.Setfailure("编辑菜单失败");
            return Json(AR, JsonRequestBehavior.DenyGet);
         
            //   return RedirectToAction("Index");

        }


        [HttpGet]
        [AllowAnonymous]
        public ActionResult EditMenu(int id)
        {
            Menu vMenu = new Menu();

            vMenu = _unit.Menus.GetById(id);
     
            MenuDTO dto = Mapper.Map<MenuDTO>(vMenu);
            return PartialView("_MenuEdit", dto);
          
         
        }

        


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult EditMenu(MenuDTO menu)
        {

            if (ModelState.IsValid)
            {
          
                Menu vMenu = Mapper.Map<Menu>(menu);
              
                Menu orgMenu = _unit.Menus.GetById(vMenu.Id);
                orgMenu.Title = vMenu.Title;
                orgMenu.MenuType = vMenu.MenuType;
                orgMenu.Active = vMenu.Active;
                orgMenu.Action = vMenu.Action;
                orgMenu.Area = vMenu.Area;
                orgMenu.CategoryId = vMenu.CategoryId;
                orgMenu.Controller = vMenu.Controller;
                orgMenu.Iconfont = vMenu.Iconfont;                  
                orgMenu.ParentId = vMenu.ParentId;
                orgMenu.Url = vMenu.Url;

                _unit.Menus.Update(orgMenu);
                _unit.SaveChanges();

                AR.SetSuccess("已成功保存菜单");
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
         
            AR.Setfailure("编辑菜单失败");
            return Json(AR, JsonRequestBehavior.DenyGet);
          
           

        }

    

        // POST: Admin/User/Delete
        [HttpPost]    
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Delete(int id)
        {

            Menu vMenu = _unit.Menus.GetById(id);
           
            if (vMenu != null)
            {
                int cid = vMenu.CategoryId;
                //string imgurl = Server.MapPath(vMenu.ImageUrl);
                //if (System.IO.File.Exists(imgurl))
                //{
                //    System.IO.File.Delete(imgurl);    //删除缩略图
                //}
                vMenu.Roles.Clear();
                _unit.Menus.Delete(vMenu);
                _unit.SaveChanges();
                var menus = await _unit.Menus.FindByAsync<int>((m => m.CategoryId == cid && m.ParentId == null), m => m.Importance, false, default(CancellationToken), (m => m.ChildMenus));
                return PartialView("_MenuList", menus);
               
            }
            AR.SetSuccess("新增菜单失败");
            return Json(AR, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UpDownMove(int id, bool isUp)
        {
            Menu vMenu = _unit.Menus.GetById(id);

            if(vMenu == null)
            {
                AR.Setfailure("菜单排位失败！");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


            if (isUp)
            {
                Menu prevMenu = _unit.Menus.GetAll().Where(m => m.ParentId == vMenu.ParentId &&
                m.Importance >= vMenu.Importance && m.Id != vMenu.Id).OrderBy(m => m.Importance).FirstOrDefault();

                if (prevMenu == null)
                {
                    AR.SetInfo("已经在第一位。");
                    return Json(AR, JsonRequestBehavior.DenyGet);
                }

                var menus = _unit.Menus.GetAll().Where(m => m.ParentId == vMenu.ParentId &&
                 m.Importance >= vMenu.Importance &&
                 m.Id != vMenu.Id &&
                 m.Id != prevMenu.Id).OrderByDescending(m => m.Importance).ToList();

                if (menus != null)
                {

                    vMenu.Importance = prevMenu.Importance + 1;
                    _unit.Menus.Update(vMenu);
                  

                    foreach (Menu m in menus)
                    {
                        m.Importance += 1;
                        _unit.Menus.Update(m);                       
                    }
                    _unit.SaveChanges();
                    //var returnMenus = await _menuService.GetMenus(vMenu.CategoryId);
                    //return PartialView("_MenuList", returnMenus);
                    AR.SetSuccess("菜单排位成功！");
                    return Json(AR, JsonRequestBehavior.DenyGet);
                }
                    
            }
            else
            {
                Menu lastMenu = _unit.Menus.GetAll().Where(m => m.ParentId == vMenu.ParentId &&
               m.Importance <= vMenu.Importance && m.Id != vMenu.Id).OrderByDescending(m => m.Importance).FirstOrDefault();
                if (lastMenu == null)
                {
                    AR.SetInfo("已经在末位。");
                    return Json(AR, JsonRequestBehavior.DenyGet);
                }
                var menus = _unit.Menus.GetAll().Where(m => m.ParentId == vMenu.ParentId &&
                 m.Importance <= vMenu.Importance &&
                 m.Id != vMenu.Id &&
                 m.Id != lastMenu.Id).OrderByDescending(m => m.Importance).ToList();
                             

                if (menus != null)
                {
                    vMenu.Importance = lastMenu.Importance - 1;
                    _unit.Menus.Update(vMenu);

                    foreach (Menu m in menus)
                    {
                        m.Importance -= 1;
                        _unit.Menus.Update(m);
                    }

                    _unit.SaveChanges();

                    AR.SetSuccess("菜单排位成功！");
                    return Json(AR, JsonRequestBehavior.DenyGet);
                }             
                
            }

            AR.Setfailure("菜单排位失败！");
            return Json(AR, JsonRequestBehavior.DenyGet);

        }




        //  [HttpPut]
        //  public JsonResult ActiveMenu(int id)
        //  {

        //      Menu vMenu = _menuService.GetById(id);

        //      try
        //      {
        //          if (vMenu != null)
        //          {
        //              vMenu.Active = !vMenu.Active;

        //              _menuService.Update(vMenu);
        //              //_unit.SaveChanges();

        //          }
        //      }
        //      catch (Exception ex)
        //      {
        //          return Json(false, JsonRequestBehavior.DenyGet);
        //      }

        //      return Json(true, JsonRequestBehavior.DenyGet);


        //  }


        protected override void Dispose(bool disposing)
        {
            this._unit.Dispose();
            base.Dispose(disposing);
        }

    }
}
